package com.studykun.client.util;

import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.TextArea;
import com.studykun.client.model.Agent;

public class Presence implements AdmitHandler, EvictHandler {
  private final Room room_;
  private final Agent agent_;
  
  public Presence(
      final Room room,
      final Agent agent) {
    room_ = room;
    agent_ = agent;
  }
  
  public Room getRoom() {
    return room_;
  }
  
  public Agent getAgent() {
    return agent_;
  }

  public void bindInput(
      final TextArea chatInput) {
    chatInput.addKeyDownHandler(new KeyDownHandler() {
      public void onKeyDown(
          final KeyDownEvent event) {
        if (KeyboardHelper.isStandardEnterKey(event)) {
          agent_.sayIn(room_, chatInput.getText());        
          chatInput.setValue("", false);
          event.stopPropagation();
          event.preventDefault();
        }
      }
    });
    chatInput.addValueChangeHandler(new ValueChangeHandler<String>() {
      public void onValueChange(ValueChangeEvent<String> event) {
        room_.echo(EchoType.PREVIEW, agent_, chatInput.getValue());
      }
    });
  }

  public void onAdmit(
      final Agent agent,
      final Room room) {
    agent_.onAdmit(agent, room);
  }

  public void onEvict(
      final Agent agent,
      final Room room) {
    agent_.onEvict(agent, room);
  }
}
